class WS {
    constructor(host) {
        this.host = host;
        this.isOpen = false;
        this.proxy = new Proxy({}, this.handler());
        this.ws = new WebSocket(this.host);
        this.regEvent();
    }

    sub(msg, cb) {
        this.proxy.msg = msg;
        this.cb = cb;

        return this;
    }

    close() {
        this.ws.close();
    }

    regEvent() {
        this.ws.onerror = (e) => {
            console.error(e);
        };

        this.ws.onopen = () => {
            this.proxy.isOpen = true;
            console.log('open', this.host);
            // this.ws.setRequestHeader('TEST', 'test');
        };

        this.ws.onmessage = (response) => {
            const { data } = response;
            if (typeof data === 'string') {
                if (this.cb) {
                    this.cb(JSON.parse(data));
                }
            } else if (data.constructor === Blob) {
                const reader = new FileReader();
                reader.onload = (event) => {
                    const { result } = event.target;
                    if (this.cb) {
                        this.cb(JSON.parse(result));
                    }
                };
                reader.readAsText(data);
            }
        };

        this.ws.onclose = () => {
            if (this.reload && typeof this.reload === 'function') {
                this.reload();
            }

            console.log('close', this.host);
        };
    }

    handler() {
        const that = this;

        return {
            set(obj, prop, value) {
                obj[prop] = value;

                if (that.proxy.msg && that.proxy.isOpen) {
                    let { msg } = that.proxy;
                    if (typeof that.proxy.msg === 'object') {
                        msg = JSON.stringify(msg);
                    }

                    that.ws.send(msg);
                }

                return true;
            },
        };
    }
}

export default WS;
